package fancyfoods.persistence;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import fancyfoods.food.Food;
import fancyfoods.food.Inventory;


public class InventoryImpl implements Inventory {

	private EntityManager entityManager;

	public void setEntityManager(EntityManager entityManager) {
		this.entityManager = entityManager;
	}

	public Food getFood(String name) {
		return entityManager.find(Food.class, name);
	}

	public List<Food> getFoodsWhoseNameContains(String name, int maxResults) {
		String query = "SELECT f FROM FOOD f WHERE f.name LIKE '%" + name
				+ "%' ORDER BY f.quantityInStock DESC";
		Query q = entityManager.createQuery(query);
		q.setMaxResults(maxResults);
		List<Food> list = q.getResultList();
		return list;
	}

	public void createFood(String name, double price, int quantity) {
		FoodImpl food = new FoodImpl(name, price, quantity);
		entityManager.persist(food);
	}

	public int removeStock(String name, int quantity) {
		// TODO Auto-generated method stub
		return 0;
	}

	public int getFoodCount() {
		Query query = entityManager.createQuery("SELECT COUNT(f) FROM FOOD f");
		Number count = (Number) query.getSingleResult();
		return count.intValue();
	}

}
